package com.jl.js.core;

import java.util.HashSet;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSFunction;
import org.mozilla.javascript.annotations.JSGetter;

public class JSHashSet extends ScriptableObject {

	private HashSet<Object> inner = new HashSet<Object>();

	public JSHashSet() {
	}

	public static Scriptable jsConstructor(Context ctx, Object[] args,
			Function ctorObj, boolean inNewExpr) throws Exception {

		if (!inNewExpr) {
			Context.reportError("HashSet() can not be called as function");
		}
		JSHashSet set = new JSHashSet();
		for (Object obj : args) {
			if (obj instanceof NativeArray) {
				NativeArray array = (NativeArray) obj;
				for (int i = 0; i < array.getLength(); i++) {
					set.getInnerSet().add(array.get(i));
				}
			} else if (obj instanceof Object[]) {
				for (Object one : (Object[]) obj) {
					set.getInnerSet().add(one);
				}
			} else {
				set.getInnerSet().add(obj);
			}
		}
		return set;
	}

	@Override
	@JSGetter
	public int size() {
		return inner.size();
	}

	@Override
	@JSFunction
	public boolean isEmpty() {
		return inner.isEmpty();
	}

	@JSFunction
	public void clear() {
		inner.clear();
	}

	@JSFunction
	public boolean add(Object e) {
		return inner.add(e);
	}

	@JSFunction
	public boolean addAll(JSHashSet c) {
		return inner.addAll(c.getInnerSet());
	}

	@JSFunction
	public boolean contains(Object o) {
		return inner.contains(o);
	}

	@JSFunction
	public boolean containsAll(JSHashSet c) {
		return inner.containsAll(c.getInnerSet());
	}

	@JSFunction
	public boolean remove(Object o) {
		return inner.remove(o);
	}

	@JSFunction
	public boolean removeAll(JSHashSet c) {
		return inner.removeAll(c.getInnerSet());
	}

	@JSFunction
	public Object[] toArray() {
		return inner.toArray();
	}

	@Override
	public String getClassName() {
		return "HashSet";
	}

	private HashSet<Object> getInnerSet() {
		return inner;
	}
}
